package com.haust.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.haust.pojo.VideoOrderPojo;
import com.haust.service.VideoOrderService;
import com.haust.util.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @Auther: csp1999
 * @Date: 2020/08/28/18:30
 * @Description: 订单 Controller
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Logger dataLogger = LoggerFactory.getLogger("dataLogger");

    @Autowired
    private VideoOrderService videoOrderService;


    /**
    * @方法描述: 支付操作,生成支付二维码
    * @参数集合: [videoId, request, response]
    * @返回类型: void
    * @作者名称: csp1999
    * @日期时间: 2020/8/30 11:55
    */
    @ResponseBody
    @GetMapping("/add")
    @CrossOrigin // 跨域
    public void saveOrder(@RequestParam(value = "video_id", required = true) int videoId,
                          HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 获取用户 客户端ip
        String ip = IPUtils.getIpAddr(request);
        // String ip = "120.25.1.43"; // 临时写死,便于测试
        String openid = (String) request.getAttribute("openid");

        // int userId = 1;// 临时写死,便于测试
        VideoOrderPojo videoOrderPojo = new VideoOrderPojo();
        videoOrderPojo.setUserId(2);// 用户下单id,这里我写死,为测试方便，可以自己写一个根据oenid 查询到userid
        videoOrderPojo.setVideoId(videoId);// 视频id
        videoOrderPojo.setIp(ip);// 用户下单ip

        // 保存订单信息，并向微信发送统一下单请求，获取二维码:codeUrl
        String codeURL = videoOrderService.save(videoOrderPojo);
        if (codeURL == null) {
            throw new NullPointerException();
        }

        try {
            // 生成二维码：
            Map<EncodeHintType, Object> hints = new HashMap<>();
            // 设置纠错等级
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            // 设置编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            // 生成二维码 google二维码生成包下
            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeURL, BarcodeFormat.QR_CODE, 400, 400, hints);

            // 通过response获得输出流
            ServletOutputStream out = response.getOutputStream();

            // 将二维码输出页面 google二维码生成包下
            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
        } catch (Exception e) {
            System.out.println("二维码生成出现异常...");
        }
    }
}
